package com.itheima.arithmetic.stack;

/**
 * 数组实现栈
 */
public class ArrayStack<Item> implements MyStack<Item> {

    private Item [] array;

    // 数组元素个数
    private int num = 0;

    public ArrayStack(int cap){
        array = (Item[]) new Object[cap];
    }

    private void judgeSize() {
        if (num >= array.length) {
            resize(2 * array.length);
        }
        else if (num > 0 && num <= array.length / 2){ // 动态收缩空间
            resize(array.length / 2);
        }
    }

    private void resize(int size){
        Item [] temp = (Item[]) new Object[size];
        for (int i = 0; i < num; i++) {
            temp [i] = array[i];
        }
        array = temp;
    }


    @Override
    public void push(Item item) {
        judgeSize();
        array[num++] = item;
    }

    @Override
    public Item pop() {
        if (isEmpty()) {
            return null;
        }
        Item item = array[--num];
        array[num] = null; // 释放空间
        return item;
    }

    @Override
    public int size() {
        return num;
    }

    @Override
    public boolean isEmpty() {
        return num == 0;
    }
}
